<script setup lang="ts">
import { ref, inject, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showConfirmDialog } from 'vant'
import logo from '@/assets/shopping-icon.svg'
import { register, sendMsgCode } from '@/api/user'
import { validatorPhone, validatorRePwd, validatorPwd } from '@/utils/validateRule'

const router = useRouter()
const $toast: any = inject('$toast', () => {})

const phone = ref('')
const password = ref('')
const rePassword = ref('')
const sms = ref('')
const handleShowPwd = ref(false)
const loading = ref(false)
const waitLoading = ref(false)
const waitTime = ref(0)
const form = ref<any>(null)
// const checked = ref(false)

watch(waitTime, (val) => {
  waitLoading.value = !!val
})

const sendMsg = async () => {
  form.value.validate("phone").then(async () => {
    await sendMsgCode({ phone: phone.value })
      .then(() => {
        waitTime.value = 1 * 60
        const timer = setInterval(() => {
          if (!waitTime.value) {
            clearInterval(timer)
            return
          }
          waitTime.value -= 1
        }, 1000)
      })
      .catch(({ message }) => $toast(message || '短信验证码发送失败'))
  })
}

const onSubmit = async(formData: any) => {
  loading.value = true
  await register({ phone: formData.phone, password: formData.password, sms: formData.sms })
    .then(() => {
      showConfirmDialog({
        title: '提示',
        message: '注册成功！是否跳转登录？',
        confirmButtonText: '确定'
      })
        .then(() => {
          router.push('/login')
        })
        .catch(() => {
        })
    })
    .catch(({ message }) => {
      $toast(message || '注册失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 注册中避免100vh造成的页面滑动
</script>

<template>
  <div>
    <div class="head-img">
      <van-image
        width="30vmax"
        fit="contain"
        :src="logo"
      />
    </div>
    <van-form ref="form" @submit="onSubmit" class="login-form">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          name="phone"
          label="手机号码"
          placeholder="手机号码"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: validatorPhone, message: '手机号格式错误' }
          ]"
        />
        <van-field
          v-model="sms"
          name="sms"
          center
          clearable
          label="短信验证码"
          placeholder="请输入短信验证码"
          :rules="[
            { required: true, message: '请输入短信验证码' },
          ]"
        >
          <template #button>
            <van-button
              @click="sendMsg"
              :loading="waitLoading"
              :loading-text="`${waitTime}s`"
              size="small"
              type="primary">发送验证码</van-button>
          </template>
        </van-field>
        <van-field
          v-model="password"
          :type="handleShowPwd ? 'text' : 'password'"
          name="password"
          label="密码"
          placeholder="密码"
          :right-icon="handleShowPwd ? 'eye-o' : 'closed-eye'"
          @click-right-icon="handleShowPwd = !handleShowPwd"
          :rules="[
            { required: true, message: '请填写密码' },
            { validator: validatorPwd },
          ]"
        />
        <van-field
          v-model="rePassword"
          type="password"
          label="确认密码"
          placeholder="密码"
          :rules="[
            { required: true, message: '请填写确认密码' },
            { validator: (val) => validatorRePwd(val, password), message: '两次输入的密码不一致' }
          ]"
        />
      </van-cell-group>
      <div style="margin: 60px 30px 0;">
        <van-button round block :loading="loading" loading-text="注册中..." type="primary" native-type="submit">
          注册
        </van-button>
      </div>
    </van-form>
    <!-- <div class="validate-bar">
      <van-checkbox v-model="checked">
        我已阅读并同意xxxx协议
      </van-checkbox>
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.head-img {
  // margin-top: 2vh;
  text-align: center;
}
.validate-bar {
  margin: 30px;
  p {
    display: flex;
    justify-content: space-between;
  }
}
.login-form {
  margin-top: 2vh;
}
</style>